package com.ibm.util;

import java.util.ArrayList;
import java.util.Collection;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.message.MessageFields;
import com.ibm.cps.newmessage.AbstractDataSourceMetadata;
import com.ibm.cps.newmessage.DataSourceMetadataFactory;
import com.ibm.factories.TimeSeriesSchemaFactory;
import com.ibm.interfaces.ITimeSeriesSchema;
import com.ibm.util.exception.CPSException;

public class PreLoadingSchemaCache extends SchemaCache {

	public ITimeSeriesSchema getSchema(String tenantid, String schemaid,ArrayList<String> type)
			throws CPSException {
		if (!schemaMap.containsKey(schemaid)) {

			Collection<String> dataSources = DataSourceMetadataFactory
					.loadExistedDataSource(tenantid);

			if (dataSources == null) {
				logger.error("No schema for schemaid " + schemaid + ".");
				return null;
			}
			for (String dataSourceStr : dataSources) {
				AbstractDataSourceMetadata dataSource = DataSourceMetadataFactory
						.parseDataSourceMetadata(dataSourceStr);
				if (dataSource.getSchemaid().equals(schemaid)) {
					ObjectNode now = (ObjectNode) JSONUtility
							.fromString(dataSource.getInput());
					ITimeSeriesSchema schema = TimeSeriesSchemaFactory
							.createFromOtherMetadata(tenantid, schemaid, now);
					schemaMap.put(schemaid, schema);
					
					// add by gxj to construct a schema parser
					if (!now.has(MessageFields.SCHEMA_FORMAT_TYPE))
						now.put(MessageFields.SCHEMA_FORMAT_TYPE, "json");
					String format = now.get(MessageFields.SCHEMA_FORMAT_TYPE).asText();
					schematypeMap.put(schemaid, format);
					type.add(format);
					
					return schema;
				}
			}

			return null;
		}

		ITimeSeriesSchema ret = schemaMap.get(schemaid);
		if (tenantid.equals(ret.getUserID())) {
			type.add(schematypeMap.get(schemaid));
			return ret;
		}
		return null;
	}
	
}
